import {
	defineStore
} from 'pinia'
import http from '@/common/request.js'
import {
	navTo,
	setLoadingToast
} from '@/common/utils'
import {
	getInfo,
	getYuShuoDetails,
	login
} from '@/api/yuShuo'

const keyNames = 'LOGISTICE_YUSHUO'

const useLogisicsYushuo = defineStore(keyNames, {
	state: () => {
		return {
			// 宇硕登录成功后的信息
			userInfo: {},
			// 存放token
			token: "",
		}
	},

	getters: {
		getUserinfo: state => state.userInfo,
		getToken: state => state.token
	},

	actions: {
		// 存储userInfo 信息
		setUserinfo(payload) {
			this.userInfo = payload
		},
		setToken(token) {
			this.token = token
		},
		clear() {
			this.userInfo = {}
			this.token = ''
		},
		// 存储userInfo 信息
		setUserinfo(payload) {
			const {
				token,
				...args
			} = payload
			this.userInfo = args
			// 如果登录成功信息中有token
			if (token) {
				this.token = token
			}
		},
		// 信息登录获取token 
		companyLogin(params) {
			const that = this
			try {
				setLoadingToast('正在登陆...')
				login(params).then(res => {
					that.setToken(res.data)
					that.getInfo()
				})
			} catch (e) {
				//TODO handle the exception
			}
		},
		// 获取司机信息
		getInfo() {
			const that = this
			try {
				getInfo().then(res => {
					// uni.hideLoading()
					// navTo("/pages/yuShuo/index/index")
					that.getDetails(res.data)
				})
			} catch (e) {
				//TODO handle the exception
				uni.hideLoading()
			}
		},
		// 获取宇硕详情
		getDetails(paramas) {
			let that = this
			try {
				getYuShuoDetails().then(res => {
					setTimeout(() => {
						that.setUserinfo({
							...paramas,
							...res.data
						})
						uni.hideLoading()
						// 前往公司首页
						navTo("/pages/yuShuo/index/index")
					}, 200)
				})
			} catch (e) {
				//TODO handle the exception
				uni.hideLoading()
			}
		},
	},
	// 数据持久化
	unistorage: true // 开启后对 state 的数据读写都将持久化
})

export default useLogisicsYushuo